package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Prod;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class ProdDao {

	private DBHelp<Prod> db = new DBHelp<Prod>();
	
	public List<Prod> findAll() {
		String sql = "select id,prodname,price from t_prod";
		return db.executeQueryForList(sql, new ProdRowMapper());
	}
	
	public Prod findById(int id) {
		String sql = "select id,prodname,price from t_prod where id = ?";
		return db.executeQueryForObject(sql, new ProdRowMapper(), id);
	}
	
	public boolean update(Prod prod) {
		String sql = "update t_prod set prodname = ?,price =? where id = ?";
		return db.executeSQL(sql, prod.getProdName(),prod.getPrice(),prod.getId());
	}
	
	public boolean save(String prodName,float price) {
		String sql = "insert into t_prod(prodname,price) values(?,?)";
		return db.executeSQL(sql, prodName,price);
	}
	
	public boolean del(int id) {
		String sql = "delete from t_prod where id = ?";
		return db.executeSQL(sql, id);
	}
	
	public List<Prod> findByOrderId(String orderId) {
		String sql = "SELECT * FROM t_prod WHERE id IN(SELECT prodid FROM t_orderItem WHERE orderid = ?)";
		return db.executeQueryForList(sql, new ProdRowMapper(), orderId);
	}
	
	private class ProdRowMapper implements RowMapper<Prod> {

		public Prod mapRow(ResultSet rs) throws SQLException {
			Prod p = new Prod();
			p.setId(rs.getInt("id"));
			p.setPrice(rs.getFloat("price"));
			p.setProdName(rs.getString("prodName"));
			return p;
		}
		
	}
}
